import React from 'react';
import { DevToolsPanel, useDevTools } from '@/utils/dev-tools';
import { Button, Card, Space, Divider, Tag, Tooltip } from 'antd';
import {
  BugOutlined,
  ClearOutlined,
  SettingOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';

interface DebugToolsProps {
  enabled?: boolean;
  position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
}

const DebugTools: React.FC<DebugToolsProps> = ({
  enabled = process.env.NODE_ENV === 'development',
  position = 'bottom-right',
}) => {
  const [isExpanded, setIsExpanded] = React.useState(false);
  const { clearLogs, metrics } = useDevTools();

  if (!enabled) {
    return null;
  }

  const getPositionStyle = () => {
    const baseStyle = {
      position: 'fixed' as const,
      zIndex: 9999,
      backgroundColor: '#1a1a1a',
      border: '1px solid #333',
      borderRadius: '8px',
      padding: '8px',
      fontFamily: 'monospace',
      fontSize: '12px',
      color: '#fff',
      minWidth: '200px',
    };

    switch (position) {
      case 'top-right':
        return { ...baseStyle, top: '20px', right: '20px' };
      case 'top-left':
        return { ...baseStyle, top: '20px', left: '20px' };
      case 'bottom-left':
        return { ...baseStyle, bottom: '20px', left: '20px' };
      default:
        return { ...baseStyle, bottom: '20px', right: '20px' };
    }
  };



  if (!isExpanded) {
    return (
      <div style={getPositionStyle()}>
        <Space>
          <Tooltip title="展开调试工具">
            <Button
              type="text"
              size="small"
              icon={<BugOutlined />}
              style={{ color: '#fff' }}
              onClick={() => setIsExpanded(true)}
            />
          </Tooltip>
        </Space>
      </div>
    );
  }

  return (
    <>
      <div style={getPositionStyle()}>
        <Card
          size="small"
          title={
            <Space>
              <BugOutlined />
              调试工具
              <Button
                type="text"
                size="small"
                icon={<ClearOutlined />}
                onClick={() => setIsExpanded(false)}
                style={{ color: '#fff', marginLeft: 'auto' }}
              />
            </Space>
          }
          style={{ backgroundColor: '#1a1a1a', borderColor: '#333' }}
          headStyle={{ backgroundColor: '#2d2d2d', borderColor: '#333', color: '#fff' }}
          bodyStyle={{ backgroundColor: '#1a1a1a', color: '#fff', padding: '8px' }}
        >

          <Divider style={{ margin: '8px 0', borderColor: '#333' }} />

          {/* 性能指标 */}
          <div style={{ marginBottom: '12px' }}>
            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>性能指标</div>
            <div style={{ maxHeight: '120px', overflowY: 'auto' }}>
              {Object.entries(metrics).map(([name, stats]) => (
                <div key={name} style={{ marginBottom: '4px', fontSize: '11px' }}>
                  <div style={{ color: '#1890ff' }}>{name.split('_').join(' ')}:</div>
                  <div style={{ marginLeft: '8px', opacity: 0.8 }}>
                    平均: {stats.avg}ms | 最小: {stats.min}ms | 最大: {stats.max}ms
                  </div>
                </div>
              ))}
              {Object.keys(metrics).length === 0 && (
                <div style={{ opacity: 0.6, fontSize: '11px' }}>暂无性能数据</div>
              )}
            </div>
          </div>

          <Divider style={{ margin: '8px 0', borderColor: '#333' }} />

          {/* 快捷操作 */}
          <div>
            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>快捷操作</div>
            <Space wrap>
              <Button
                type="text"
                size="small"
                icon={<ClearOutlined />}
                onClick={clearLogs}
                style={{ color: '#fff' }}
              >
                清空日志
              </Button>
              <Button
                type="text"
                size="small"
                icon={<SettingOutlined />}
                onClick={() => {
                  const panel = document.getElementById('dev-tools-panel');
                  if (panel) {
                    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
                  }
                }}
                style={{ color: '#fff' }}
              >
                详细面板
              </Button>
            </Space>
          </div>

          {/* 快捷键提示 */}
          <div style={{ marginTop: '8px', fontSize: '10px', opacity: 0.6 }}>
            <InfoCircleOutlined /> 快捷键: Ctrl+Shift+D (调试工具) | Ctrl+Shift+C (清空日志)
          </div>
        </Card>
      </div>


      {/* 详细调试面板 */}
      <DevToolsPanel />
    </>
  );
};

// 性能监控组件
export const PerformanceMonitor: React.FC = () => {
  const { metrics } = useDevTools();

  return (
    <Card
      size="small"
      title="性能监控"
      style={{ backgroundColor: '#1a1a1a', borderColor: '#333' }}
      headStyle={{ backgroundColor: '#2d2d2d', borderColor: '#333', color: '#fff' }}
      bodyStyle={{ backgroundColor: '#1a1a1a', color: '#fff', padding: '8px' }}
    >
      <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
        {Object.entries(metrics).map(([name, stats]) => (
          <div key={name} style={{ marginBottom: '8px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
              <span style={{ color: '#1890ff' }}>{name.split('_').join(' ')}</span>
              <Tag color="blue" style={{ fontSize: '10px' }}>
                {stats.count}次
              </Tag>
            </div>
            <div style={{ display: 'flex', gap: '8px', fontSize: '11px', opacity: 0.8 }}>
              <span>平均: {stats.avg}ms</span>
              <span>最小: {stats.min}ms</span>
              <span>最大: {stats.max}ms</span>
            </div>
          </div>
        ))}
        {Object.keys(metrics).length === 0 && (
          <div style={{ textAlign: 'center', opacity: 0.6 }}>暂无性能数据</div>
        )}
      </div>
    </Card>
  );
};

// 组件调试信息组件
export const ComponentDebugInfo: React.FC<{
  componentName: string;
  props?: Record<string, any>;
  state?: Record<string, any>;
}> = ({ componentName, props, state }) => {
  const [isVisible, setIsVisible] = React.useState(false);

  if (process.env.NODE_ENV !== 'development') {
    return null;
  }

  return (
    <div style={{ position: 'relative', marginBottom: '8px' }}>
      <Button
        type="text"
        size="small"
        onClick={() => setIsVisible(!isVisible)}
        style={{
          position: 'absolute',
          top: '-20px',
          right: '0',
          fontSize: '10px',
          color: '#666',
        }}
      >
        <BugOutlined />
      </Button>

      {isVisible && (
        <Card
          size="small"
          title={`组件调试: ${componentName}`}
          style={{
            position: 'absolute',
            top: '0',
            right: '0',
            width: '300px',
            zIndex: 1000,
            backgroundColor: '#1a1a1a',
            borderColor: '#333',
          }}
          headStyle={{ backgroundColor: '#2d2d2d', borderColor: '#333', color: '#fff' }}
          bodyStyle={{ backgroundColor: '#1a1a1a', color: '#fff', padding: '8px' }}
        >
          {props && (
            <div style={{ marginBottom: '8px' }}>
              <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Props:</div>
              <pre style={{ fontSize: '10px', whiteSpace: 'pre-wrap' }}>
                {JSON.stringify(props, null, 2)}
              </pre>
            </div>
          )}
          {state && (
            <div>
              <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>State:</div>
              <pre style={{ fontSize: '10px', whiteSpace: 'pre-wrap' }}>
                {JSON.stringify(state, null, 2)}
              </pre>
            </div>
          )}
        </Card>
      )}
    </div>
  );
};

// 导出默认组件
export default DebugTools;